package com.sls.api.game.servlet.downstream;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.api.game.constant.Constant;
import com.sls.api.game.constant.ExCodeDes;
import com.sls.api.game.pojo.Goods;
import com.sls.api.game.pojo.UserInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.api.util.IpUtil;
import com.sls.api.util.OrganizeRespXmlData;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.SecretKeyUtil;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 详细商品信息查询
 * 
 * @author cx
 * 
 */
public class DetailGoodsQueryServlet extends SuperServlet {

	private static final long serialVersionUID = -1039940270284312448L;
	private static Logger log = Logger.getLogger(DetailGoodsQueryServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 合作方用户账号
		String userNo = req.getParameter("userNo");
		if (StringUtils.isNotEmpty(userNo)) {
			userNo = userNo.trim();
		}
		// 商品编号
		String goodsId = req.getParameter("goodsId");
		if (StringUtils.isNotEmpty(goodsId)) {
			goodsId = goodsId.trim();
		}
		// 签名字符串
		String sign = req.getParameter("sign");
		if (StringUtils.isNotEmpty(sign)) {
			sign = sign.trim();
		}

		boolean flag = this.validateData(userNo, goodsId, sign, resp, req);
		if (flag) // 数据校验成功
		{
			try {
				Gson gson = CommonUtil.gson();
				SocketDTO dto = orgGsonSocket(userNo, goodsId, req);

				Head head = dto.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();

				Goods goods = null;
				String body = dto.getBody();
				if (StringUtils.isNotEmpty(body)) {
					goods = gson.fromJson(body, Goods.class);
				}
				if (goods == null) {
					ResponseDataXmlFormat.returnFailMsg(
							ExCodeDes.UNKNOW_ERROR.getCode(),
							ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
					return;
				}
				if (!(Constant.SUCCESS.equals(resCode))) {
					resCode = ExCodeDes.UNKNOW_ERROR.getCode();
				}
				String xmlData = OrganizeRespXmlData
						.assembleXmlForGoodsDetailQuery(resCode, resMsg, goods);
				resp.getWriter().write(xmlData);
				resp.getWriter().flush();
				resp.getWriter().close();

			} catch (Exception e) {
				log.error(e.toString());
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.UNKNOW_ERROR.getCode(),
						ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
			}
		}

	}

	/**
	 * 组织gson报文
	 * 
	 * @param userId
	 * @param userPwd
	 * @param sign
	 * @param req
	 * @return
	 */
	private SocketDTO orgGsonSocket(String userNo, String goodsId,
			HttpServletRequest req) {
		UserInfo user = new UserInfo();
		user.setUserNo(userNo);
		user.setGoodsId(goodsId);
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.QUERY_GOODS_DETAIL);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId(userNo);
		return super.send(head, user);
	}

	/**
	 * 数据校验
	 * 
	 * @param userId
	 * @param userPwd
	 * @param sign
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	private boolean validateData(String userNo, String goodsId, String sign,
			HttpServletResponse resp, HttpServletRequest req)
			throws IOException {
		boolean result = false;
		if (StringUtils.isEmpty(userNo)) {
			log.info("商品详细信息查询时,合作方用户账号为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[userId]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(goodsId)) {
			log.info("商品详细信息查询时,商品编号为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[goodsId]!",
					resp);
			return false;
		} else if (StringUtils.isEmpty(sign)) {
			log.info("商品详细信息查询时,签名字符串为空!!!");
			ResponseDataXmlFormat.returnFailMsg(
					ExCodeDes.PARAMETER_EMPTY.getCode(),
					ExCodeDes.PARAMETER_EMPTY.getDescription() + "[sign]!",
					resp);
			return false;
		} else {
			StringBuilder builder = new StringBuilder();
			builder.append(userNo);
			builder.append(goodsId);
			String secretKey = SecretKeyUtil.getInstance().getKey(userNo, req);
			if (StringUtils.isNotEmpty(secretKey)) {
				builder.append(secretKey);
			} else {
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.UNKNOW_ERROR.getCode(),
						ExCodeDes.UNKNOW_ERROR.getDescription(), resp);
				return false;
			}
			String data = builder.toString();

			boolean checked = UtilMD5Encryption.checkMD5SignatureOfUTF8(data,
					sign);
			if (checked) {
				result = true;
			} else {
				log.info("商品详细信息查询时,数字签名验证失败!!!");
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.SIGN_FAIL.getCode(),
						ExCodeDes.SIGN_FAIL.getDescription(), resp);
				return false;
			}
		}
		if (StringUtils.isNotEmpty(goodsId)) {
			boolean f = this.goodsExist(goodsId, userNo, req);
			if (!f) {
				log.info("此商品暂不可用!!!");
				ResponseDataXmlFormat.returnFailMsg(
						ExCodeDes.GOODS_NOT_EXIST.getCode(),
						ExCodeDes.GOODS_NOT_EXIST.getDescription(), resp);
			} else {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 判断此商品是否存在
	 * 
	 * @param goodsId
	 * @param userId
	 * @param req
	 * @return
	 */
	private boolean goodsExist(String goodsId, String userNo,
			HttpServletRequest req) {
		boolean exist = false;
		UserInfo user = new UserInfo();
		user.setGoodsId(goodsId);
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.QUERY_GOODS_BY_ID);
		head.setIp(req.getRemoteAddr());
		head.setUserId(userNo);
		SocketDTO dto = super.send(head, user);
		if (Constant.SUCCESS.equals(dto.getHead().getResponseCode())) {
			exist = true;
		}
		return exist;
	}

}
